package com.ruoyi.api.service;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.api.domain.HyToken;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.api.mapper.HyTokenMapper;
import com.ruoyi.system.domain.HyUser;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Api用户信息Service业务层处理
 *
 * @author lixin
 * @date 2021-06-19
 */
@Service
public class ApiTokenService  extends ServicePlusImpl<HyTokenMapper, HyToken> {

	/**
	 * 30天过期
	 */
	private final static Long EXPIRE = 3600 * 24 * 30L;


	/**
	 * 创建token信息
	 * @param user
	 * @return
	 */
	public String createToken(HyUser user) {
		//生成一个token
		String token = IdUtil.simpleUUID();
		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		HyToken tokenEntity = baseMapper.queryByUserId(user.getUserId());
		if (tokenEntity == null) {
			tokenEntity = new HyToken();
			tokenEntity.setUserId(user.getUserId());
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
			//保存token
			baseMapper.insert(tokenEntity);
		} else {
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
			//更新token
			baseMapper.updateById(tokenEntity);
		}
		return token;
	}

	/**
	 * 根据token查询
	 * @param token
	 * @return
	 */
	public HyToken queryByToken(String token) {
		return baseMapper.queryByToken(token);
	}



}
